package com.hongxun.project.assets.iLine.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.hongxun.common.utils.text.Convert;
import com.hongxun.project.assets.b10kvLineInfo.domain.B10kvLineInfo;
import com.hongxun.project.assets.b10kvLineInfo.service.IB10kvLineInfoService;
import com.hongxun.project.assets.bByq.domain.BByq;
import com.hongxun.project.assets.bByq.service.IBByqService;
import com.hongxun.project.assets.bDivice.domain.BDivice;
import com.hongxun.project.assets.bDivice.service.IBDiviceService;
import com.hongxun.project.assets.bMaterial.domain.BMaterial;
import com.hongxun.project.assets.bMaterial.service.IBMaterialService;
import com.hongxun.project.assets.iDevice.domain.IDevice;
import com.hongxun.project.assets.iDevice.service.IIDeviceService;
import com.hongxun.project.assets.iMaterial.domain.IMaterial;
import com.hongxun.project.assets.iMaterial.service.IIMaterialService;
import com.hongxun.project.assets.iPicture.domain.IPicture;
import com.hongxun.project.assets.iPicture.service.IIPictureService;
import com.hongxun.project.assets.iPoint.domain.IPoint;
import com.hongxun.project.assets.iPoint.service.IIPointService;
import com.hongxun.project.assets.iPullLine.domain.IPullLine;
import com.hongxun.project.assets.iPullLine.service.IIPullLineService;
import com.hongxun.project.assets.pBoxes.domain.PBoxes;
import com.hongxun.project.assets.pBoxes.service.IPBoxesService;
import com.hongxun.project.assets.pCablePit.domain.PCablePit;
import com.hongxun.project.assets.pCablePit.service.IPCablePitService;
import com.hongxun.project.assets.pDevice.domain.PDevice;
import com.hongxun.project.assets.pDevice.service.IPDeviceService;
import com.hongxun.project.assets.pMaterial.domain.PMaterial;
import com.hongxun.project.assets.pMaterial.service.IPMaterialService;
import com.hongxun.project.assets.pPicture.domain.PPicture;
import com.hongxun.project.assets.pPicture.service.IPPictureService;
import com.hongxun.project.assets.pPoint.domain.PPoint;
import com.hongxun.project.assets.pPoint.service.IPPointService;
import com.hongxun.project.assets.pPullLine.domain.PPullLine;
import com.hongxun.project.assets.pPullLine.service.IPPullLineService;
import com.hongxun.project.assets.pTask.service.IPTaskService;
import com.hongxun.project.system.dict.domain.DictData;
import com.hongxun.project.system.dict.service.IDictDataService;
import com.hongxun.project.system.role.domain.Role;
import com.hongxun.project.system.user.domain.User;
import com.hongxun.project.system.user.service.IUserService;
//import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hongxun.framework.aspectj.lang.annotation.Log;
import com.hongxun.framework.aspectj.lang.enums.BusinessType;
import com.hongxun.project.assets.iLine.domain.ILine;
import com.hongxun.project.assets.iLine.service.IILineService;
import com.hongxun.framework.web.controller.BaseController;
import com.hongxun.framework.web.page.TableDataInfo;
import com.hongxun.framework.web.domain.AjaxResult;
import com.hongxun.common.utils.poi.ExcelUtil;

/**
 * 低压线路 信息操作处理
 * 
 * @author hongxun
 * @date 2019-03-19
 */
@Controller
@RequestMapping("/assets/iLine")
public class ILineController extends BaseController
{
    private String prefix = "assets/iLine";
	
	@Autowired
	private IILineService iLineService;
	@Autowired
	private IBByqService bByqService;
	@Autowired
	private IB10kvLineInfoService b10kvLineInfoService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IPPointService pPointService;
	@Autowired
	private IIPointService iPointService;
	@Autowired
	private IPMaterialService pMaterialService;
	@Autowired
	private IPDeviceService pDeviceService;
	@Autowired
	private IPPictureService pPictureService;
	@Autowired
	private IIPictureService iPictureService;
	@Autowired
	private IBDiviceService bDiviceService;
	@Autowired
	private IBMaterialService bMaterialService;
	@Autowired
	private IIMaterialService iMaterialService;

	@Autowired
	private IPTaskService pTaskService;
    @Autowired
    private IPCablePitService pCablePitService;
    @Autowired
    private IPBoxesService pBoxesService;
	@Autowired
	private IPPullLineService pPullLineService;
	@Autowired
	private IIPullLineService iPullLineService;
	@Autowired
	private IIDeviceService iDeviceService;
	@Autowired
	private IDictDataService dictDataService;


	
	@RequiresPermissions("assets:iLine:view")
	@GetMapping()
	public String iLine()
	{
	    return prefix + "/iLine";
	}

	@GetMapping("iLineMap")
	public String iLineMap()
	{
		return prefix + "/iLineMap";
	}

	/**
	 * 线路选择列表
	 * @return
	 */
	@GetMapping("/chooseLineForId/{id}/{byqId}")
	public String chooseLineForId(@PathVariable("id") String id ,@PathVariable("byqId") String byqId ,  ModelMap modelMap)
	{
		modelMap.put("id2",id);
		modelMap.put("byqId",byqId);
	    return prefix + "/chooseLineForId";
	}
	@GetMapping("/chooseLine")
	public String chooseLine()
	{
		return prefix + "/chooseLine";
	}

	/**
	 * 	变压器下所挂支线路
	 * @return
	 */
	@PostMapping("/sonLine")
	@ResponseBody
	public List sonLine(@RequestParam Map<String , Object> map)
	{
		String byq_id = map.get("byq_id").toString();
		ILine iLine = new ILine();
		iLine.setByqId(byq_id);
		List<ILine> iLineList = iLineService.selectILineList(iLine) ;
	    return iLineList;
	}


	/**
	 * 线路信息--点位杆塔编辑页面跳转
	 * @return
	 */
	@GetMapping("/showGt/{id}")
	public String showGt(@PathVariable("id") String id , ModelMap modelMap)
	{
		modelMap.put("pointId",id);					// 点位ID
	    return prefix + "/GtDetailed";
	}

	/**
	 * 线路信息--下户点编辑页面跳转
	 * @return
	 */
	@GetMapping("/showXhd/{id}")
	public String showXhd(@PathVariable("id") String id , ModelMap modelMap)
	{
		modelMap.put("pointId",id);					// 点位ID
	    return prefix + "/XhdDetailed";
	}

	/**
	 * 线路信息--分支箱编辑页面跳转
	 * @return
	 */
	@GetMapping("/showFzx/{id}")
	public String showFzx(@PathVariable("id") String id , ModelMap modelMap)
	{
		modelMap.put("pointId",id);					// 点位ID
	    return prefix + "/FzxDetailed";
	}


	/**
	 * 线路信息--点位变压器编辑页面跳转
	 * @return
	 */
	@GetMapping("/showByq/{id}")
	public String showByq(@PathVariable("id") String id , ModelMap modelMap)
	{
		modelMap.put("pointId",id);					// 点位ID
        return prefix + "/byqDetailed";
	}

	/**
	 * 线路信息--点位表箱编辑页面跳转
	 * @return
	 */
	@GetMapping("/showBx/{id}")
	public String showBx(@PathVariable("id") String pointId , ModelMap modelMap)
	{
		PBoxes pBoxes = new PBoxes();
		pBoxes.setPId(pointId);
		pBoxes.setDatastate("删除");
		List<PBoxes> list = pBoxesService.selectPBoxesList(pBoxes);
		for (PBoxes boxes : list) {
        	modelMap.put("Id",boxes.getId());				// ID
        	modelMap.put("pointId",boxes.getPId());			// 点位ID
		}
//		modelMap.put("taskId",taskId);

	    return prefix + "/BoxesDetailed";
	}

	/**
	 * 线路信息--点位电缆井编辑页面跳转
	 * @return
	 */
	@GetMapping("/showDlj/{id}")
	public String showDlj(@PathVariable("id") String pointId , ModelMap modelMap)
	{
        PCablePit pCablePit = new PCablePit();
        pCablePit.setPId(pointId);
		pCablePit.setDatastate("删除");
		List<PCablePit> list = pCablePitService.selectPCablePitList(pCablePit);
		for (PCablePit cablePit : list) {
			modelMap.put("Id",cablePit.getId());			// ID
			modelMap.put("pointId",cablePit.getPId());		// 点位ID
		}
//		modelMap.put("taskId",taskId);

	    return prefix + "/CablePitDetailed";
	}


	/**
	 * 线路信息--交叉跨越编辑页面跳转
	 * @return
	 */
	@GetMapping("/showJcky/{id}")
	public String showJcky(@PathVariable("id") String id ,ModelMap modelMap)
	{
		modelMap.put("pointId",id);					// 点位ID
//		modelMap.put("taskId",taskId);
	    return prefix + "/CrossoverDetailed";
	}


	/**
	 * 线路名称回显
	 * @param
	 * @return
	 */
	@PostMapping("/getLineName")
	@ResponseBody
	public Map<String , Object> getLineName(ILine iLine)
	{

		Map<String , Object> newMap = new HashMap<>();
		List<ILine> iLines = iLineService.selectILineList(iLine);
		newMap.put("iLines", iLines);
		return newMap;
	}


	/**
	 * 查询低压线路列表
	 */
	@RequiresPermissions("assets:iLine:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ILine iLine)
	{
		startPage();
		List<ILine> iLines = new ArrayList<>();
		if(getUserId() != 1) {
//			iLines = iLineService.selectByqFom(getUserId(),null);
			iLine.setUsersId(getUserId().toString());
			iLines = iLineService.selectByqFomss(iLine);
		}else
			iLines = iLineService.selectILineList(iLine);

		return getDataTable(iLines);
	}

	/**
	 * 修改任务选线路--只显示当前变压器下的线路
	 *
	 * @param iLine
	 * @return
	 */
	@PostMapping("/listForTask")
	@ResponseBody
	public TableDataInfo listForTask(ILine iLine)
	{
		String byqId = iLine.getByqId();
		startPage();
		List<ILine> iLines = new ArrayList<>();
//		if(getUserId() != 1)
//			iLines = iLineService.selectByqFom(getUserId(),null);
//		else
			iLines = iLineService.selectILineList(iLine);

		return getDataTable(iLines);
	}

	/**
	 * 	不显示当前线路的线路列表
	 *
	 * @param id
	 * @param iLine
	 * @return
	 */
	@PostMapping("/listForId/{id}/{byqId}")
	@ResponseBody
	public TableDataInfo listForId(@PathVariable("id") String id ,@PathVariable("byqId") String byqId , ILine iLine , Map<String , Object> map)
	{
		iLine.setId(id);
		iLine.setByqId(byqId);
		startPage();
		List<ILine> iLines = new ArrayList<>();
		if(getUserId() != 1) {
			iLine.setUsersId(getUserId().toString());
			iLines = iLineService.selectByqFomss(iLine);
		}
		else
			iLines = iLineService.selectILineListNoThis(iLine);

		return getDataTable(iLines);
	}
	
	
	/**
	 * 导出低压线路列表
	 */
	@RequiresPermissions("assets:iLine:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ILine iLine)
    {
    	List<ILine> list = iLineService.selectILineList(iLine);
        ExcelUtil<ILine> util = new ExcelUtil<ILine>(ILine.class);
        return util.exportExcel(list, "iLine");
    }
	
	/**
	 * 新增低压线路
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存低压线路
	 */
	@RequiresPermissions("assets:iLine:add")
	@Log(title = "低压线路", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(ILine iLine)
	{
		iLine.setAddUser(getUserId().intValue());
		iLine.setAddDate(new Date());
		iLine.setDatastate("新增");
		return toAjax(iLineService.insertILine(iLine));
	}

	/**
	 * 修改低压线路
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap)
	{
		ILine iLine = iLineService.selectILineById(id);
		ILine iLiness = iLineService.selectILineById(iLine.getUpLineId());
		if(iLiness!=null) iLine.setUpLineName(iLiness.getName());
		//  2019/3/21  已知变压器id和上级线路id，求变压器名称和上级线路名称,返回页面进行展示
		B10kvLineInfo b10kvLineInfo = b10kvLineInfoService.selectB10kvLineInfoById(iLine.getUpLineId());
		BByq bByq = bByqService.selectBByqById(iLine.getByqId());
		if(bByq == null)
			iLine.setByqName("");
		else
			iLine.setByqName(bByq.getName());
		if(b10kvLineInfo != null)
			iLine.setUpLineName(b10kvLineInfo.getName());
		mmap.put("iLine", iLine);
		mmap.put("byqId",iLine.getByqId());
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存低压线路
	 */
	@RequiresPermissions("assets:iLine:edit")
	@Log(title = "低压线路", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(ILine iLine)
	{		
		return toAjax(iLineService.updateILine(iLine));
	}
	
	/**
	 * 删除低压线路
	 */
	@RequiresPermissions("assets:iLine:remove")
	@Log(title = "低压线路", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		String[] lineId = Convert.toStrArray(ids);
		//	判断该线路下是否还有子线路，如有，则无法删除
		for (String s : lineId) {
			ILine iLine = new ILine();
			iLine.setUpLineId(s);
			List<ILine> iLines = iLineService.selectILineList(iLine);
			if(iLines.size()>0){
				return error("线路下挂有其他线路信息，不能删除该线路！");
			}
		}

		//	删除线路时，先判断线路下是否有点位，有点位不能被删除，无点位时可以被删除
		PPoint pPoint = new PPoint();
		pPoint.setDatastate("删除");
		for (String s : lineId) {
			pPoint.setLineId(s);
			List<PPoint> pPointList = pPointService.selectPPointList(pPoint);
			if (pPointList.size() != 0) {
				return error("线路下有点位信息，不能删除！");
			}
		}

		return toAjax(iLineService.deleteILineByIds(ids));
	}


	/**
	 * 采集人、任务创建/分配人名称回显
	 * @param map
	 * @return
	 */
	@PostMapping("/getCreateLineUserName")
	@ResponseBody
	public Map<String , Object> getCreateLineUserName(@RequestParam Map<String, Object> map)
	{
		Map<String , Object> newMap = new HashMap<>();
		List<User> userList = userService.selectUserList(new User());
		newMap.put("userList", userList);
		return newMap;
	}


	/**
	 * 	低压线路点位预选
	 * @param objectMap
	 * @return
	 */
	@PostMapping("linePoint")
	@ResponseBody
	public List<IPoint> linePoint(@RequestParam Map<String , Object> objectMap){

		String byqId = "";
		if(!objectMap.get("byqId").equals(""))
			byqId = objectMap.get("byqId").toString();
		String lineId = "";
		if(!objectMap.get("lineId").equals(""))
			lineId = objectMap.get("lineId").toString();
		String lineName = "";
		if(!objectMap.get("lineName").equals(""))
			lineName = objectMap.get("lineName").toString();
		List<IPoint> iPointList = new ArrayList<>();
		List<IPoint> iPointListss = new ArrayList<>();
		List<IPoint> iPointList1 = new ArrayList<>();
		IPoint iPoint = new IPoint();
		iPoint.setByqId(byqId);
		iPoint.setLineId(lineId);
		if(lineId.equals("") || lineName==""){
			iPointList = iPointService.selectIPointList(iPoint);
			iPointListss = iPointList;
		}else{
			iPointList = iPointService.selectIPointList(iPoint);

			for (IPoint point : iPointList) {
				IPoint iPoint1 = new IPoint();
				iPoint1.setLineId(point.getLineId());
				iPoint1.setId(point.getUpId());
				iPointList1 = iPointService.selectIPointList(iPoint1);
				if(iPointList1.size() == 0){
					IPoint iPoint3 = iPointService.selectIPointById(point.getUpId());
					iPointListss.add(iPoint3);
					iPointListss.add(point);

				}else{
					iPointListss.add(point);
				}

			}
		}
		/*if(iPointList.size() > 0){
			for (IPoint point : iPointList) {
				if(point.getType().equals("同杆架设")){
					IPoint iPoint2 = iPointService.selectIPointById(point.getPoleId());
					point.setCode(iPoint2.getCode());
				}
			}
		}*/


		int pto = 0;
		for (IPoint point : iPointListss) {
			pto++;
			if(point.getType().equals("同杆架设")){
				IPoint iPoint2 = iPointService.selectIPointById(point.getPoleId());
				ILine iLine = iLineService.selectILineById(point.getLineId());
				ILine iLine1 = iLineService.selectILineById(iPoint2.getLineId());
				if (iLine != null && iLine1 != null){
					String xlw = iLine.getName()+","+iLine1.getName();
					point.setLineName(xlw);
				}
				point.setCode(iPoint2.getCode());
			}else{
				if(!(point.getType().equals("杆塔") && point.getIsPole().equals("是"))){
					if(pto % 3 == 0 ){
						ILine iLine = iLineService.selectILineById(point.getLineId());
						if(iLine !=null) point.setLineName(iLine.getName());
					}
				}
			}
		}

		for (IPoint point : iPointListss) {
			if( point.getPullNum()!=null){
				if(point.getPullNum()>0){
					IPullLine iPullLine = new IPullLine();
					iPullLine.setPId(point.getId());
					List<IPullLine> pullLineList = iPullLineService.selectIPullLineList(iPullLine);
					for (IPullLine pullLine : pullLineList) {
						point.setLxLgt(pullLine.getLgt());
						point.setLxLat(pullLine.getLat());
					}
				}
			}
		}

		return iPointListss;
	}



	/**
	 * 	材料选择页面
	 * @return
	 */
	@GetMapping("getAllMaterial")
	public String getAllMaterial(){
		return prefix+"/MaterialDetailed";
	}


	/**
	 * 	设备选择页面
	 * @return
	 */
	@GetMapping("getAllDivicel")
	public String getAllDivicel(){
		return prefix+"/DeviceDetailed";
	}



	/**
	 *  添加材料
	 *
	 * @param
	 * @return
	 */
	@PostMapping("addMaterial")
	@ResponseBody
	public AjaxResult addMaterial(@RequestParam Map<String , Object> objectMap){
		String materialIds = objectMap.get("materialId").toString();	//	材料ID
		String pointId = objectMap.get("pointId").toString();			//	点位ID
		String lineId = objectMap.get("lineId").toString();				//	低压线路ID
		String byqId = objectMap.get("byqId").toString();				//	所属变压器ID
		String[] materialId = materialIds.split(",");

		IMaterial iMaterial = new IMaterial();
		int i = 0;
		for (String s : materialId) {
			//	从材料库查询所选材料
			BMaterial bMaterial = bMaterialService.selectBMaterialById(s);
			//	将查询出对应的材料添加到点位材料采集数据库

			iMaterial.setBMaterialId(bMaterial.getId());
			iMaterial.setPointId(pointId);
			iMaterial.setLineId(lineId);
			iMaterial.setByqId(byqId);
			iMaterial.setBigType(bMaterial.getBigType());
			iMaterial.setMidType(bMaterial.getMidType());
			iMaterial.setLable(bMaterial.getLable());
			iMaterial.setName(bMaterial.getName());
			iMaterial.setModle(bMaterial.getModle());
			iMaterial.setCode(bMaterial.getCode());
			iMaterial.setUnit(bMaterial.getUnit());
			iMaterial.setPrice(bMaterial.getPrice());
			iMaterial.setCount(BigDecimal.ONE);
			iMaterial.setTechParameter(bMaterial.getTechParameter());
			iMaterial.setReleaseStatus(bMaterial.getReleaseStatus());
			iMaterial.setAddUser(Integer.parseInt(getUserId().toString()));
			iMaterial.setAddDate(new Date());
			iMaterial.setDatastate("新增");

			i = iMaterialService.insertIMaterial(iMaterial);

		}

		return toAjax(i);
	}



	/**
	 *  添加设备
	 *
	 * @param
	 * @return
	 */
	@PostMapping("addDivice")
	@ResponseBody
	public AjaxResult addDivice(@RequestParam Map<String , Object> objectMap){
		String devicelIds = objectMap.get("divicelId").toString();		//	设备ID
		String pointId = objectMap.get("pointId").toString();			//	点位ID
		String lineId = objectMap.get("lineId").toString();				//	低压线路ID
		String byqId = objectMap.get("byqId").toString();				//	所属变压器ID
		String[] devicelId = devicelIds.split(",");

		IDevice iDevice = new IDevice();
		int i = 0;
		for (String s : devicelId) {
			//	从设备库查询所选设备
			BDivice bDivice = bDiviceService.selectBDiviceById(s);
			//	将查询出对应的设备添加到设备采集数据库

			iDevice.setBDiveceId(bDivice.getId());
			iDevice.setPointId(pointId);
			iDevice.setLineId(lineId);
			iDevice.setByqId(byqId);
			iDevice.setBigType(bDivice.getBigType());
			iDevice.setMidType(bDivice.getMidType());
			iDevice.setLable(bDivice.getLable());
			iDevice.setName(bDivice.getName());
			iDevice.setModle(bDivice.getModle());
			iDevice.setCode(bDivice.getCode());
			iDevice.setUnit(bDivice.getUnit());
			iDevice.setPrice(bDivice.getPrice());
			iDevice.setTechParameter(bDivice.getTechParameter());
			iDevice.setAddUser(Integer.parseInt(getUserId().toString()));
			iDevice.setAddDate(new Date());
			iDevice.setDatastate("新增");

			i = iDeviceService.insertIDevice(iDevice);

		}

		return toAjax(i);
	}




	/**
	 *  获取照片
	 */
	@GetMapping("getPicture/{pointId}")
	public String getPicture(@PathVariable("pointId") String id , ModelMap modelMap){
		modelMap.put("pointId",id);
		return prefix+"/picture";
	}

	@PostMapping("getssPicture")
	@ResponseBody
	public List getssPicture(@RequestParam String pointId ){
		IPicture iPicture = new IPicture();
		iPicture.setPId(pointId);
		List<IPicture> iPictureList = iPictureService.selectIPictureList(iPicture);

		List<DictData> dictDataList = dictDataService.selectDictDataForSort(pointId);
		//  排序
		if(iPictureList.size() > 0){
			for (IPicture picture : iPictureList) {
				for (DictData dictData : dictDataList) {
					if(picture.getType().equals(dictData.getDictLabel())){
						picture.setSort(dictData.getDictSort().intValue());
						iPictureService.updateIPicture(picture);
					}
				}
			}
		}
		List<IPicture> iPictureListss = iPictureService.selectListOrderByType(iPicture);

		return iPictureListss;
	}

}
